﻿using System;
using System.Net;
using System.Web;
using System.IO;
using DataAccessObject;
using System.Data;
using System.Collections.Generic;
using System.Text;
using ThangNM_LIB.FUNC;
using Newtonsoft.Json;

namespace API
{
    /// <summary>
    /// Summary description for Resource
    /// </summary>

    public class Resource : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            try
            {
                //if (Convert.ToString(context.Request.QueryString["sRID"]).Contains("js"))
                //{
                //    getDataGeoJson(context);
                //    return;
                //}
                if (!String.IsNullOrEmpty(context.Request.QueryString["api"]))
                {
                    search_viaroute_OSM(context);
                    return;
                }

                String sFileName = getAppSettings("sPathSaveMap", "D:\\") + "{0}\\{1}\\{2}\\{3}.png";
                String sRID = Convert.ToString(context.Request.QueryString["sRID"]).Trim();
                if (!String.IsNullOrEmpty(sRID))
                {
                    String sUrlBase = "http://{0}.tile.openstreetmap.org/{1}/{2}/{3}.png";
                    String[] aPart = sRID.Split('_');
                    if (aPart.Length == 4)
                    {
                        sRID = String.Format(sUrlBase, aPart[0], aPart[1], aPart[2], aPart[3]);
                        sFileName = String.Format(sFileName, aPart[0], aPart[1], aPart[2], aPart[3]);
                    }
                    else
                        goto _404;
                    HttpResponse r = context.Response;
                    r.ContentType = "image/png";
                    byte[] bTemp;
                    if (getAppSettings("isUseOnlineMap", "9").Equals("1"))
                        using (WebClient client = new WebClient())
                        {
                            if (getAppSettings("isUseProxy", "9").Equals("1"))
                            {
                                WebProxy proxy = new WebProxy("proxy.fis.vn", 8080);
                                proxy.Credentials = new NetworkCredential("fis\\ThangNM11", "Th@n9NM!!");
                                //proxy.UseDefaultCredentials = true;
                                proxy.BypassProxyOnLocal = true;
                                client.Proxy = proxy;
                            }
                            bTemp = client.DownloadData(sRID);
                            if (getAppSettings("isAutoSaveMap", "9").Equals("1"))
                                if (!File.Exists(sFileName) || getAppSettings("isAutoUpdateMap", "9").Equals("1"))
                                {
                                    if (!Directory.Exists(Path.GetDirectoryName(sFileName)))
                                        Directory.CreateDirectory(Path.GetDirectoryName(sFileName));
                                    File.WriteAllBytes(sFileName, bTemp);
                                }
                            r.OutputStream.Write(bTemp, 0, bTemp.Length);
                        }
                    else
                    {
                        bTemp = File.ReadAllBytes(sFileName);
                        r.OutputStream.Write(bTemp, 0, bTemp.Length);
                    }
                    r.Cache.SetCacheability(HttpCacheability.Public);
                    r.Cache.SetLastModified(DateTime.Now);
                    return;
                }

            _404:
                context.Response.StatusCode = 404;
                context.Response.StatusDescription = "Not Found";
                return;
            }
            catch (Exception ex)
            {
                context.Response.StatusCode = 520;
                context.Response.StatusDescription = "Unknown Error";
                return;
            }
        }

        public static String getAppSettings(String sKey, String sDefault = "")
        {
            if (System.Configuration.ConfigurationManager.AppSettings[sKey] != null)
                return System.Configuration.ConfigurationManager.AppSettings[sKey];
            else
                return sDefault;
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        public void getDataGeoJson(HttpContext context)
        {
            HttpResponse r = context.Response;
            r.ContentType = "application/x-javascript";

            DataTable dt = (new ECustomsDAO()).SelectList();
            if (dt != null && dt.Rows.Count > 0)
            {
                String sRet = "var planes = " + JsonConvert.SerializeObject(dt);
                //List<object> chartData = new List<string,string,string,string>();
                // //chartData.Add(new object[] { "NAME", "TOTAL" });
                // foreach (DataRow dr in dt.Rows)
                // {
                //     //chartData = new   dr["PK_iCID"], dr["sName"], dr["iContainer"], dr["dLatitude"], dr["dLongitude"] });
                // }
                byte[] bTemp = Encoding.ASCII.GetBytes(sRet);
                r.OutputStream.Write(bTemp, 0, bTemp.Length);
                r.Cache.SetCacheability(HttpCacheability.Public);
                r.Cache.SetLastModified(DateTime.Now);
            }
            else
            {
                context.Response.StatusCode = 520;
                context.Response.StatusDescription = "Unknown Error";
            }
        }



        public void search_viaroute_OSM(HttpContext context)
        {
            HttpResponse r = context.Response;
            r.ContentType = "application/x-javascript; charset=UTF-8";
            String sUrlBase = "";
            switch (context.Request.QueryString["api"])
            {
                case "osm":
                    sUrlBase = "http://router.project-osrm.org/viaroute" + context.Request.Url.Query.Replace("&api=osm", "");
                    break;
                case "nominatim":
                    sUrlBase = "http://nominatim.openstreetmap.org/search/" + context.Request.Url.Query.Replace("&api=nominatim", "");
                    break;
                case "bing":
                    sUrlBase = "http://dev.virtualearth.net/REST/v1/Locations" + context.Request.Url.Query.Replace("&api=bing", "");
                    break;
                case "google":
                    sUrlBase = "https://maps.googleapis.com/maps/api/geocode/json" + context.Request.Url.Query.Replace("&api=google", "");
                    break;
                default:
                    context.Response.StatusCode = 404;
                    context.Response.StatusDescription = "Not Found";
                    break;
            }
            //if (context.Request.Url.Query.Contains("instructions"))
            //    sUrlBase = "http://router.project-osrm.org/viaroute" + context.Request.Url.Query;
            //else if (context.Request.Url.Query.Contains("q="))
            //    sUrlBase = "http://nominatim.openstreetmap.org/search/" + context.Request.Url.Query;
            //else
            //{
            //    context.Response.StatusCode = 404;
            //    context.Response.StatusDescription = "Not Found";
            //    return;
            //}

            if (context.Response.StatusCode != 404)
            {
                using (WebClient client = new WebClient())
                {
                    if (getAppSettings("isUseProxy", "9").Equals("1"))
                    {
                        WebProxy proxy = new WebProxy("proxy.fis.vn", 8080);
                        proxy.Credentials = new NetworkCredential("fis\\ThangNM11", "Th@n9NM!!");
                        //proxy.UseDefaultCredentials = true;
                        proxy.BypassProxyOnLocal = true;
                        client.Proxy = proxy;
                    }
                    byte[] bTemp = client.DownloadData(sUrlBase);
                    r.OutputStream.Write(bTemp, 0, bTemp.Length);
                }
                r.Cache.SetCacheability(HttpCacheability.Public);
                r.Cache.SetLastModified(DateTime.Now);
            }
        }
    }
}